<?php

namespace App\Http\Repository;

use App\BannerLabel;

class BannerRepository
{
    private $bannerLabel;

    public function __construct(BannerLabel $bannerLabel)
    {
        $this->bannerLabel = $bannerLabel;
    }

    //得到按标签归类的banner列表
    public function getBannerGroupLabel()
    {
        $srcSql = <<<sql
SELECT
  banners.label,
  images.path AS image,
  banners.id,
  banners.status,
  banners.xindex,
  banners.updated_at,
  banners.tag,
  admins.name AS author
FROM banners
  JOIN images ON images.id = banners.image
  JOIN admins ON admins.id = banners.author
sql;

        $tmpBanner = $this->bannerLabel
            ->leftJoin(
                \DB::raw('(' . $srcSql . ') as one'),
                'one.label', '=', 'banner_labels.id')
            ->select('banner_labels.id as label_id', 'banner_labels.name as label_name', 'one.*')
            ->orderBy('banner_labels.id')
            ->orderBy('one.xindex', 'DESC')
            ->get();

        foreach ($tmpBanner as $banner) {
            $banners[$banner->label_id]['name'] = $banner->label_name;
            if (!empty($banner->id)) {
                $banners[$banner->label_id]['data'][] = $banner;
            }
        }

        return $banners;
    }

    //得到按path归类的banner列表
    public function getBannerGroupPath()
    {
        $srcSql = <<<sql
SELECT
  banners.label,
  images.path AS image,
  banners.id,
  banners.url,
  banners.tag,
  banners.status,
  banners.xindex,
  admins.name AS author
FROM banners
  JOIN images ON images.id = banners.image
  JOIN admins ON admins.id = banners.author
WHERE banners.status=1
sql;

        $tmpBanner = $this->bannerLabel
            ->leftJoin(
                \DB::raw('(' . $srcSql . ') as one'),
                'one.label', '=', 'banner_labels.id')
            ->select('banner_labels.id as label_id', 'banner_labels.name as label_name', 'banner_labels.path as label_path', 'one.*')
            ->where('banner_labels.status', 1)
            ->orderBy('one.xindex','DESC')
            ->get()
            ->toArray();
        $banners = [];
        foreach ($tmpBanner as $banner) {
            if (!empty($banner['id'])) {
                $banners[$banner['label_path']][] = $banner;
            }
        }
        return $banners;
    }
}